package com.wiki.gds.user.provider.modular.sys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.wiki.gds.base.common.utils.StringUtil;
import com.wiki.gds.base.security.admin.utils.SecurityUtil;
import com.wiki.gds.user.facade.sys.model.Dept;
import com.wiki.gds.user.facade.sys.model.query.DeptQuery;
import com.wiki.gds.user.facade.sys.vo.DeptVo;
import com.wiki.gds.user.provider.modular.sys.mapper.DeptDao;
import com.wiki.gds.user.provider.modular.sys.service.DeptService;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.engine.PageQuery;
import org.beetl.sql.core.query.Query;
import org.beetl.sql.core.query.QueryCondition;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author:wiki
 * @Date:Create in 2018/7/20 0020 上午 10:32
 */
@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptDao deptDao;

    @Autowired
    private SQLManager sqlManager;


    @Override
    public Long insert(Dept dept) {
        dept.setCreateTime(new Date());
        dept.setCreateBy(SecurityUtil.getSecurityUser().getId());



        Long rs= deptDao.insertReturnKey(dept).getLong();
        return rs;
    }

    @Override
    public Boolean update(Dept dept) {
        dept.setUpdateTime(new Date());
        dept.setUpdateBy(SecurityUtil.getSecurityUser().getId());
        Integer rs=  deptDao.updateTemplateById(dept);
        return rs>0?true:false;
    }

    @Override
    public Boolean del(Dept dept) {
        return null;
    }

    @Override
    public Dept getById(Long id) {
        return deptDao.single(id);
    }

    @Override
    public List<Dept> getList(Map map) {
        Query<Dept> query= sqlManager.query(Dept.class);
        query.andNotEq("status","-1");
//        map.forEach((key, value) -> {
//            query.andEq((String)key,value);
//        });
        List<Dept> list=query.select();

        return query.select();
    }

    @Override
    public void getPageList(PageQuery query) {

    }

    public List<DeptVo> deptTree(List<Dept> list, DeptVo parentDeptVo){
        List<DeptVo> tree=new ArrayList<>();
          for(Dept item:list){
              if(item.getPid().equals(parentDeptVo.getId())){
                  List<Long> pids=new ArrayList<>();
                  if(parentDeptVo.getPids()!=null&&parentDeptVo.getId()!=0){
                      for(Long a:parentDeptVo.getPids()){
                          pids.add(a);
                      }
                  }else {
                      List<Long> pidArray =new ArrayList<>();
                      pidArray.add(parentDeptVo.getId());
                      parentDeptVo.setPids(pidArray);
                  }
                  pids.add(parentDeptVo.getId());
                  DeptVo deptVo=new DeptVo();
                  deptVo.setPids(pids);
                  BeanUtils.copyProperties(item,deptVo);
                  List<DeptVo> child=deptTree(list,deptVo);
                  deptVo.setChildren(child.size()>0?child:null);
                  tree.add(deptVo);
              }
          }
//
//          list.forEach(item->{
//
//          });

          return tree;
    }

    @Override
    public Long getCount(Dept dept) {
        return null;
    }

    @Override
    public Dept getBySelf(Dept dept) {
        return null;
    }

    @Override
    public Long saveOrUpdate(Dept dept) {
        if(dept.getPid()==null){
            dept.setPid(SecurityUtil.getSecurityUser().getDeptId());
        }
        if(dept.getPid()==0) {
             dept.setPids("[0]");
        }else {
             Dept parent=getById(dept.getPid());
             String pids=parent.getPids();
             pids+=",["+dept.getPid()+"]";
             dept.setPids(pids);
        }
        if(StringUtil.isEmpty(dept.getId())) {
            this.insert(dept);
            return null;
        }else {
            this.update(dept);
            return null;
        }
    }

    @Override
    public List<DeptVo>  treeByPid(DeptQuery deptQuery) {
        Long deptId= deptQuery.getDeptId();
        String sql="select * from sys_dept where status!=-1 and (pids like CONCAT('%[',#deptId#,']%') or id=#deptId#)";
        if(StrUtil.isNotEmpty(deptQuery.getName())){
            sql+=" and simple_name like CONCAT('%',#name#,'%')";
        }
        sql+=" order by LENGTH(pids)";
        List<Dept> list=sqlManager.execute(sql,Dept.class,BeanUtil.beanToMap(deptQuery,false,true));
        DeptVo deptVo=new DeptVo();
        deptVo.setId(deptId);
        if(deptId==0){
               if(list!=null){
                   if(list.get(0).getPid()==0){
                       deptVo.setPid(0l);
                       deptVo.setId(0l);
                       deptVo.setSimpleName("顶层");
                       deptVo.setFullName("顶层");
                   }
                   else {
                       BeanUtils.copyProperties(list.get(0),deptVo);
                   }
               }else {
                   deptVo.setPid(0l);
                   deptVo.setId(0l);
                   deptVo.setSimpleName("顶层");
                   deptVo.setFullName("顶层");
               }
        }else {
            if(list.size()>0){
                BeanUtils.copyProperties(list.get(0),deptVo);
            }
        }
        List<DeptVo> child=deptTree(list,deptVo);
        deptVo.setChildren(child.size()>0?child:null);
//        return deptVo;
        List<DeptVo> deptVoList=new ArrayList<>();
        deptVoList.add(deptVo);
        return deptVoList;
    }

    @Override
    public List<Long> deptIdsByPid(Long pid) {
        Map map=new HashMap();
        map.put("pid",pid);
        String sql="select id from sys_dept where pids like CONCAT('%[',#pid#,']%') or id=#pid#";
        List<Long> ids=sqlManager.execute(sql,Long.class,map);
        return ids;
    }
}
